﻿using B.S.BasicData.Infrastructure.Implement;
using B.S.BasicData.Infrastructure.Interface;
using Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Claims;
using System.Text;

namespace B.S.BasicData.Api.Read.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            services.AddAutoMapper(typeof(MyMapper));
            services.AddScoped<JwtTools>();
            return services;
        }
        /// <summary>
        /// 上下文扩展方法
        /// </summary>
        /// <typeparam name="MyDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqlLog">是否打印执行ef语句转义的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextServices<MyDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where MyDbContext : DbContext
        {
            return services.AddDbContext<MyDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                        );
                });
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((categroy, level) => categroy == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });
        }

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:Secretkey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = builder.Configuration["Authentication:Audience"],

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }

       
         
    
    }
}
